package com.visionork.android;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.visionork.rss.FeedParser;
import com.visionork.rss.FeedParserFactory;
import com.visionork.rss.Message;
import com.visionork.rss.ParserType;

import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class WhatNewActivity extends ListActivity {
	private List<Message> messages;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		loadFeed();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		String url = messages.get(position).getLink().toExternalForm();
		String title = messages.get(position).getTitle();
		
		Intent intent = new Intent(this, ShowActivity.class);
		intent.putExtra(ShowActivity.url_key, url);
		intent.putExtra(ShowActivity.title_key, title);
		startActivity(intent);		
	}

	private void loadFeed() {
		FeedParser parser = FeedParserFactory.getParser(ParserType.TW);
		messages = parser.parse();
		List<String> titles = new ArrayList<String>(messages.size());
		for (Message msg : messages) {
			titles.add(msg.getTitle());
		}
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				R.layout.row, titles);
		this.setListAdapter(adapter);
	}

	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add("Refresh");
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		super.onMenuItemSelected(featureId, item);
		loadFeed();
		Toast.makeText(getApplicationContext(), "Refresh", Toast.LENGTH_SHORT)
				.show();
		return true;
	}

}
